package com.hrt.datasender.datadao.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.btcode.db.executer.IDataExecuter;
import com.btcode.db.result.Row;
import com.btcode.db.sqlparameter.SQLParameterList;
import com.btcode.orm.executer.IORMExecuter;
import com.hrt.datasender.datadao.model.BdSourceModel;
import com.hrt.db.DBManager;

public final class BdDataCommonService {

    private static volatile BdDataCommonService instance;

    private BdDataCommonService() {

    }

    public static BdDataCommonService getInstance() {
        if (instance == null) {
            synchronized (BdDataCommonService.class) {
                if (instance == null) {
                    instance = new BdDataCommonService();
                }
            }
        }
        return instance;
    }

    /**
     * 获取指定数据表，一个时间段内的数据
     * 
     * @param tableName
     * @param start
     * @param end
     * @return
     */
    public List<BdSourceModel> getData(String tableName, Date start, Date end) {

        IORMExecuter ormExecuter = DBManager.getORMExecuter();

        String datasql = " SELECT * FROM BD_SOURCE WHERE DATATIME > @start and DATATIME <= @end order by DATATIME DESC ";
        SQLParameterList pc = new SQLParameterList();
        pc.put("start", start);
        pc.put("end", end);

        List<BdSourceModel> models = ormExecuter.getModelListSQL(datasql, pc, BdSourceModel.class);

        return models;
    }

    /**
     * 获取一段时间内的统计信息
     * 
     * @param start
     * @param end
     * @return
     */
    public List<Row> getStaticsData(String tableName, Date start, Date end) {
        IDataExecuter dataExecuter = DBManager.getDataExecuter();

        String datasql = " SELECT AVG(MEAS_RE) MEAS_AVG,AVG(MEAS_ZS) MEAS_ZS_AVG,PARAM_CODE_BUS,MAX(DATATIME) DATATIME FROM "
                + tableName + " WHERE DATATIME > @start and DATATIME <= @end group by PARAM_CODE_BUS ";
        SQLParameterList pc = new SQLParameterList();
        pc.put("start", start);
        pc.put("end", end);

        List<Row> models = dataExecuter.queryList(datasql, pc);

        return models;
    }

    /**
     * 获取一段时间内最新一组数据
     * 
     * @param start
     * @param end
     * @return
     */
    public List<BdSourceModel> getLastSourceData(String tableName, Date start, Date end) {
        List<BdSourceModel> result = new ArrayList<>();
        List<BdSourceModel> sourceDatas = getData(tableName, start, end);

        if (sourceDatas == null || sourceDatas.size() <= 0) {
            return null;
        }

        BdSourceModel firstDataModel = sourceDatas.get(0);
        result.add(firstDataModel);

        for (int i = 1; i < sourceDatas.size(); i++) {
            BdSourceModel model = sourceDatas.get(i);
            if (model.getDatatime().equals(firstDataModel.getDatatime())) {
                result.add(model);
            }
        }

        return result;
    }
}